local BenzhenLayer = {}

BenzhenLayer.__index = BenzhenLayer

require "Util/GameUtil"
local config = require "Benzhen/BenzhenConfig"

function BenzhenLayer:new()
	local object = {}
	setmetatable(object, BenzhenLayer)

	return object
end

function BenzhenLayer:config(point, point1, point2)
	local vectorX = {x = point1.x - point.x, y = point1.y - point.y}
	local vectorY = {x = point2.x - point.x, y = point2.y - point.y}

	local lengthX = gameMath.length(vectorX.x, vectorX.y)
	local lengthY = gameMath.length(vectorY.x, vectorY.y)

	self:setGrid(config.grid.x, config.grid.y)
	self:setLength(lengthX, lengthY)
	self:setGridLength(lengthX / config.grid.x, lengthY / config.grid.y)

	self.vectorX = {}
	self.vectorY = {}
	self.vectorX.x, self.vectorX.y = gameMath.normalize(vectorX.x, vectorX.y)
	self.vectorY.x, self.vectorY.y = gameMath.normalize(vectorY.x, vectorY.y)

	print("grid x "..self.gridX.." grid y"..self.gridY)
	print("lengthX "..self.lengthX.." lengthY "..self.lengthY)
	print("gridLengthX "..self.gridLengthX.." gridLengthY "..self.gridLengthY)
	print("vectorX.x "..self.vectorX.x.." vectorX.y "..self.vectorX.y)
	print("vectorY.y "..self.vectorY.x.." vectorY.y "..self.vectorY.y)
end

function BenzhenLayer:setGrid(x,y)
	self.gridX = x
	self.gridY = y
end

function BenzhenLayer:setLength(x,y)
	self.lengthX = x
	self.lengthY = y
end

function BenzhenLayer:setGridLength(x,y)
	self.gridLengthX = x
	self.gridLengthY = y
end

function BenzhenLayer:setPosition(x,y)
	self.posX = x
	self.posY = y
end

function BenzhenLayer:getPosition(x, y, sizeX, sizeY)
	--print(x,y,sizeX,sizeY)
	local px = self.vectorX.x * (x + sizeX/2) * self.gridLengthX + self.vectorY.x * (y + sizeY/2) * self.gridLengthY
	local py = self.vectorX.y * (x + sizeX/2) * self.gridLengthX + self.vectorY.y * (y + sizeY/2) * self.gridLengthY
	--print(px,py)
	return px, py
end

function BenzhenLayer:getGrid(x,y)
	local gx = (x * self.vectorY.y - self.vectorY.x * y) / (self.vectorX.x * self.vectorY.y - self.vectorY.x * self.vectorX.y) / self.gridLengthX
	local gy = (x * self.vectorX.y - self.vectorX.x * y) / (self.vectorY.x * self.vectorX.y - self.vectorX.x * self.vectorY.y) / self.gridLengthY
	
	local gx = gameMath.floor(gx)
	local gy = gameMath.floor(gy)

	local gx = gameMath.limit(gx, 0, self.gridX)
	local gy = gameMath.limit(gy, 0, self.gridY)

	print("BenzhenLayer getGrid ", x, y, gx, gy)

	return gx, gy
end


return BenzhenLayer